<template>
  <div class="createPost-container">
    <el-form class="form-container" :model="form" :rules="rules" ref="refForm" label-width="80px">

      <el-form-item label="账户类型:" prop="">
        <el-radio-group v-model="form.userType">
          <el-radio-button
            v-for="item in consts.ACCOUNT_TYPE"
            :key="item.value"
            :label="item.value">{{item.title}}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="弹窗类型:" prop="dialogType">
        <el-select v-model="dialogType" placeholder="请选择弹窗类型" @change="handleDialogTypeChange">
          <el-option v-for="item in dialogTypeSelect"
                     :key="item.value"
                     :label="item.title"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="显示端:" prop="showClient">
        <el-select v-model="form.showClient" placeholder="请选择显示端" :multiple="true" :style="{width: '270px'}">
          <el-option v-for="item in consts.ADVER_DEVICE_TYPE_ACTIVE"
                     v-if="item.value !== -1"
                     :key="item.value"
                     :label="item.title"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="添加图片:" prop="content" v-if="dialogType === 1">
        <editorImage color="#1890ff" @successCBK="handlePicUrl" :limit="1"></editorImage>
      </el-form-item>

      <div class="img-wrapper" v-if="imgList.length > 0">
        <!--        <img v-for="(item, index) of imgList" :key="index" :src="item.url" alt="">-->
        <div class="img-item" v-for="(item, index) of imgList" :key="index">
          <img class="img-pre" :src="item.url" alt="">
          <div class="img-shadow">
            <i class="el-icon-delete" @click="handleImgDelete(index.url)"></i>
          </div>
        </div>
      </div>

      <div class="link-wrapper">
        <el-form-item label="跳转:" prop="actionPlat" v-if="dialogType === 1" class="form-item">
          <el-select v-model="form.actionPlat">
            <el-option v-for="item in consts.linkType"
                       :key="item.value"
                       :label="item.title"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="form-item link-input" prop="actionTarget" v-if="dialogType === 1">
          <el-input type="text" v-model.trim="form.actionTarget" class="link"></el-input>
        </el-form-item>
      </div>

      <el-form-item label="主题:" prop="name">
        <el-input type="textarea" :rows="1" class="article-textarea" autosize placeholder="请输入内容"
                  v-model="form.name">
        </el-input>
      </el-form-item>

      <el-form-item label="简介:" prop="summary">
        <el-input type="textarea" :rows="1" class="article-textarea" autosize placeholder="请输入内容"
                  v-model="form.summary">
        </el-input>
      </el-form-item>
      <!--<el-form-item label="链接地址" prop="url">-->
      <!--<el-input type="textarea" :rows="1" class="article-textarea" autosize placeholder="请输入链接地址"-->
      <!--v-model="form.url">-->
      <!--</el-input>-->
      <!--<el-tip>提示：内链直接填路径名，外链加http://，空链可不填。 填写即为跳转专题页活动。</el-tip>-->
      <!--</el-form-item>-->

      <!-- <el-form-item label="弹窗背景:" prop="form">
        <img :src="form.bgImage" v-if="form.bgImage" class="image"/>
        <editor-image color="#1890ff" class="editor-upload-btn"
                      :limit="1"
                      @successCBK="imageSuccessCBK"></editor-image>
        <el-tip>支持gif、jpg、png格式，大小不超过2M. 最多可添加一张，背景尺寸 800*500</el-tip>
      </el-form-item> -->

      <el-form-item label="内容:" prop="content" v-if="dialogType === 0">
        <Tinymce :height=400 ref="editor" v-model="form.content"/>
      </el-form-item>

      <el-form-item label="时间周期:" class="postInfo-container-item" prop="time">
        <el-date-picker
          v-model="form.time"
          class="filter-item"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
          align="right">
        </el-date-picker>
        <el-tip>在此时间周期内，每天用户第一次登录时，显示弹窗消息</el-tip>
      </el-form-item>
      <el-button v-loading="loading" style="margin-left: 10px;" type="primary"
                 @click="handleSubmit">确定
      </el-button>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce';
// import EditorImage from '@/components/Tinymce/components/editorImage';
import editorImage from '@/components/Tinymce/components/editorImage';


import {
  noticeDashboardNormalDialogEditApi as editApi,
  noticeDashboardNormalDialogSaveApi as saveApi,
} from '@/services/api/notice';
import { form, factory } from '@/build';
import CheckboxAll from '@/components/CheckboxAll/index';
import weditor from '@/components/WEditor/index';

export default {
  name: 'dashboard-normal-notice',
  components: {
    CheckboxAll,
    Tinymce,
    editorImage,
    // weditor,
    // EditorIm
    // age,
  },

  mixins: [form],

  props: ['id', 'rowData'],
  data() {
    return {
      userListOptions: [],
      selectAll: false,
      isIndeterminate: false,
      dialogType: 0,
      imgList: [],
      form: {
        id: this.id,
        userType: -1,
        summary: undefined,
        showClient: [],
        name: undefined,
        bigImage: undefined,
        content: undefined,
        url: undefined,
        time: undefined,
        contentType: 0,
        actionType: 0,
        actionTarget: undefined,
        actionPlat: undefined,
        dialogType: 0,
      },
      rules: {
        // actionTarget: { required: true, message: '跳转路径必须选择' },
        dialogType: { required: true, message: '弹窗类型必须选择' },
        // actionPlat: { required: true, message: '跳转平台必须选择' },
        userType: { required: true, message: '账户类型必须选择' },
        showClient: { required: true, message: '显示端必须选择' },
        summary: { required: true, message: '简介必须填写' },
        name: { required: true, message: '主题必须填写' },
        // url: factory.getRule('uri'),
        content: { required: true, message: '内容必须填写' },
        time: { required: true, message: '时间周期必须选择' },
      },
    };
  },
  computed: {
    dialogTypeSelect() {
      return this.form.userType === 0 ? consts.DIALOG_TYPE : [
        { title: 'html', value: 0 },
      ];
    },
  },
  watch: {
    'form.userType': {
      handler(val) {
        if (val === 1 || val === -1) {
          this.dialogType = 0;
          this.setType(0);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    if (!_.isUndefined(this.rowData)) {
      const {
        showClientArray, startTime, endTime, actionTarget, content, contentType,
      } = this.rowData;
      let actionPlat; let
        target;
      if (actionTarget) {
        const obj = JSON.parse(actionTarget);
        actionPlat = _.find(consts.linkType, { content: obj.type }).value;
        target = obj.target;
      }
      if (content && contentType && contentType === 1) {
        this.imgList = [{ url: content }];
      }
      this.form = {
        ...this.rowData,
        showClient: showClientArray,
        time: [moment(startTime).format('YYYY-MM-DD HH:mm:ss'), moment(endTime).format('YYYY-MM-DD HH:mm:ss')],
        actionPlat,
        actionTarget: target,
      };
      this.setType(contentType);
    }

    this.bindSave(saveApi, 'saveForm', 'form', {
      beforeSend: (data) => {
        const {
          showClient, time, actionPlat, actionTarget,
        } = data;
        const linkTypeKeys = consts.linkType.map(item => item.value);
        let target;
        if (linkTypeKeys.includes(actionPlat) && actionTarget) {
          data.actionType = 1;
          target = JSON.stringify({ type: _.find(consts.linkType, { value: actionPlat }).content, target: actionTarget });
        }

        let startTime;
        let endTime;
        if (!_.isUndefined(time) && _.isArray(time)) {
          startTime = time[0];
          endTime = time[1];
        }
        return {
          ...data, showClient: showClient.join(','), startTime, endTime, actionTarget: target || actionTarget,
        };
      },
      afterSuccess: () => {
        this.imgList = [];
        this.resetForm('refForm');
        this.$emit('on-success');
        if (!this.form.id) {
          this.$router.push({
            path: '/notice/notice-pop',
            replace: true,
            query: {
              tab: 'one',
            },
          });
        }
      },
    });
  },
  methods: {
    typeAllChange(val) {
      this.form.type = val ? [1, 2] : [];
      this.isIndeterminate = false;
    },

    typeChange(value) {
      const checkedCount = value.length;
      this.selectAll = checkedCount === 2;
      this.isIndeterminate = checkedCount > 0 && checkedCount < 2;
    },

    imageSuccessCBK(arr) {
      arr.forEach((picInfo) => {
        this.form.bigImage = picInfo.url;
      });
    },

    setImg(arr, flag) {
      let str = '';
      _.forEach(arr, (item) => {
        // str += `<img class="wscnph" src="${item.url}" >`;
        str += `${item.url},`;
        flag && this.imgList.push({ url: item.url });
      });
      // this.form.content = '<p>' + str + '</p>'
      this.form.content = str.substring(0, str.length - 1);
    },

    setType(val) {
      this.dialogType = val;
      this.form.dialogType = val;
      this.form.contentType = val;
      this.form.actionType = val;
    },

    handleDialogTypeChange(val) {
      this.setType(val);
      this.imgList = [];
      this.resetForm('refForm');
    },

    handlePicUrl(arr) {
      this.setImg(arr, true);
    },

    handleImgDelete(url) {
      const index = _.findIndex(this.imgList, { url });
      this.imgList.splice(index, 1);
      this.setImg(this.imgList, false);
    },

    handleSubmit() {
      this.doSave({
        action: 'saveForm',
        form: {
          name: 'refForm',
          scrollToError: true,
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
  /deep/ .el-form-item__label {
    width: 85px !important;
  }

  /deep/ .el-form-item__content {
    margin-left: 90px !important;
  }

  .image {
    width: 100px;
    height: 100px;
  }

  .img-wrapper {
    margin: 5px 0 5px 85px;
    border-radius: 6px;
    border: 1px solid #dcdfe6;
    padding: 10px;
    display: flex;
    flex-wrap: wrap;

    .img-item {
      width: 150px;
      height: 150px;
      position: relative;
      margin-right: 5px;

      .img-pre {
        width: 100%;
        height: 100%;
        vertical-align: top;
      }

      .img-shadow {
        display: none;
        color: #fff;
        font-size: 22px;
        text-align: center;
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        top: 0;
        background: rgba(0, 0, 0, .5);
        line-height: 150px;

        i {
          cursor: pointer;
        }
      }

      &:hover {
        .img-shadow {
          display: block;
        }
      }
    }

  }

  .link-wrapper {
    overflow: hidden;

    .link-input {
      margin-left: 20px;

      /deep/ .el-form-item__content {
        margin-left: 0px !important;
      }

      .link {
        width: 500px;
      }
    }

    .form-item {
      float: left;

    }
  }
</style>
